<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElInput, ElButton,ElMessageBox,ElMessage,   } from 'element-plus'
import { getProcessTemplateList,getBpmnFile,deleteProcessTemplate,addProcessTemplate } from "@/api/ProcessTemplate.js"
import XmlViewer from 'vue3-xml-viewer'; // 导入 XML 查看器
import axios from 'axios';
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import {Plus, Refresh, Search} from '@element-plus/icons-vue'

const baseURL = ref('http://127.0.0.1:8081');
//xml的内容
const xmlContent = ref("");
// xmlz展示的配置选项
const viewerOptions = ref({
  theme: 'light', // 主题：light 或 dark
  indentation: 2, // 缩进空格数
  hoverEffect: true, // 悬停效果
  expandLevel: 2, // 初始展开层级
});

interface ProcessTemplate {
  id: number  
}
//图片弹框
const pngData = reactive({
  dialogVisible:false,
  imageUrl:"",
})
//xml弹框
const xmlData = reactive({
  dialogVisible:false,
  data:"",
})

// 表格数据
const tableData = ref([])
// 生命周期钩子
onMounted(() => {
  //获取列表
  getProcessTemplateListData()
  
})

const getProcessTemplateListData = () => {
  getProcessTemplateList().then(res => {
    console.log("模板列表",res)
    if (res.code === 200) {
      tableData.value = res.data
    }
  })
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchParams = reactive({
  name: '',
  model: ''
})

// 加载数据
const loadData = async () => {
  try {
    // 模拟API调用
    tableData.value = []
    pagination.total = tableData.value.length
  } catch (error) {
    console.error('数据加载失败')
  }
}

// 搜索重置
const resetSearch = () => {
  searchParams.name = ''
  searchParams.model = ''
  //loadData()
}

//编辑
const handleDelete = (row:ProcessTemplate)=>{
  ElMessageBox.confirm( '确定删除该流程信息吗?',  '系统警告',    {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteProcessTemplate(row.id).then(()=>{
      ElMessage.success("删除成功")
      getProcessTemplateListData()
    })
  }).catch(() => {
    console.log('取消删除')
  })


}

//查看流程图
const handleShowPng =  (row:ProcessTemplate) => {
  pngData.dialogVisible = true

  pngData.imageUrl = `/api/process/template/getBpmnFile/${row.id}/png`
  
};

//查看流程图
const handleShowXml = async (row:ProcessTemplate) => {
  xmlData.dialogVisible = true
  axios.get( `/api/process/template/getBpmnFile/${row.id}/xml`)
  .then(response=>{
    console.log(response)
    xmlContent.value  = response.data
  })

};
// 新增数据
const template = reactive({ 
  dialogVisible:false
})
//打开新增流程对话框
const toAdd = ()=>{
  template.dialogVisible = true
}
//新增流程部署
interface RuleForm {
  templateName: string
  templateType: string
  processDefinitionPath:string
  description:string
  file:string | Blob
}

//流程新增
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  templateName: '',
  templateType: '',
  processDefinitionPath:'',
  description:'',
  file:'' //上传文件
})
//手动验证上传文件
const validateFile = (rule: any, value: any, callback: any) => {
  console.log(ruleForm.file,"validateFile")
  if(ruleForm.file.name == null){
    callback(new Error('请选择上传文件'))
  }else{
    let fileName = ruleForm.file.name;
    if(fileName.lastIndexOf(".zip")==-1){
      callback(new Error('上传文件格式为zip的文件'))
      return
    }
  }
  
  callback()
}
const rules = reactive<FormRules<RuleForm>>({
  templateName: [{
      required: true,
      message: '请输入流程名称',
      trigger: 'change',
    }],
  templateType: [{
      required: true,
      message: '请选择流程类型',
      trigger: 'change',
    }],
  description: [
    {
      required: true,
      message: '请输入描述信息',
      trigger: 'change',
    }],
  file: [
    {
      required: true,
      validator: validateFile, 
      trigger: 'change',
    }],
})
//表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let formData = new FormData()
      formData.append("templateName",ruleForm.templateName)
      formData.append("templateType",ruleForm.templateType)
      formData.append("description",ruleForm.description)
      formData.append("file",ruleForm.file.raw)
      addProcessTemplate(formData).then(res=>{
        ElMessage.success(res.message)
        template.dialogVisible = false
        getProcessTemplateListData()
        //清空表单
        clearRuleForm()
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//文件上传===================
const fileList = ref<UploadUserFile[]>([])

const clearRuleForm = ()=>{
  ruleForm.templateName=''
  ruleForm.templateType= ''
  ruleForm.processDefinitionPath=''
  ruleForm.description=''
  ruleForm.file='' //上传文件
  fileList.value = []
}
//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


//移除文件的时候
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles,"handleRemove")
}
//选择文件的时候
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile,"handlePreview")
  ruleForm.file = uploadFile
  //ruleForm.processDefinitionPath = uploadFile.name
}




</script>

<template>
  <div class="">
    <el-form :inline="true" :model="searchParams" class="demo-form-inline" style="margin-top: 10px;">
      <el-form-item>
        <el-space>
          <!--        <el-input-->
          <!--          v-model="searchParams.name"-->
          <!--          placeholder="请输入流程名称"-->
          <!--          style="width: 230px; "-->
          <!--          clearable-->
          <!--          :prefix-icon="Search"-->
          <!--        />-->
          <!--          <el-input-->
          <!--              v-model="searchParams.model"-->
          <!--              placeholder="请输入型号"-->
          <!--              style="width: 230px; "-->
          <!--              clearable-->
          <!--          />-->
          <!--          <el-button type="primary" :icon="Search" @click="loadData">-->
          <!--            搜索-->
          <!--          </el-button>-->
          <!--          <el-button type="primary" plain :icon="Refresh" @click="resetSearch">-->
          <!--            重置-->
          <!--          </el-button>-->
          <el-button plain type="primary" :icon="Plus" @click="toAdd">
            新增
          </el-button>
        </el-space>
      </el-form-item>
    </el-form>
    <el-table :data="tableData">
      <el-table-column prop="templateName" label="流程名称" align="left"/>
      <el-table-column prop="templateType" label="流程类型" align="center"/>
      <el-table-column prop="processDefinitionKey" label="流程定义key" align="center"/>
      <el-table-column prop="processVersion" label="版本" align="center"/>
      <el-table-column prop="description" label="流程描述" align="center"/>
      <el-table-column prop="description" label="流程文件" align="center" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleShowXml(scope.row)">
          <el-icon><el-icon-edit /></el-icon>查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="流程图" align="center" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleShowPng(scope.row)">
          <el-icon><el-icon-edit /></el-icon>查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <el-button link type="danger" @click="handleDelete(scope.row)">
            <el-icon><el-icon-delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      layout="slot, prev, pager, next, "
      style="margin-top: 20px"
    >
      <el-text key="1">总条数：{{ pagination.total }}</el-text>
    </el-pagination>-->
    <!--查看流程图-->
    <el-dialog
      v-model="pngData.dialogVisible"
      title="查看流程图"
      width="500" >
      <el-image :src="pngData.imageUrl" fit="contain"/>
    </el-dialog>

    <!--查看流程xml的文件-->
    <el-dialog
      v-model="xmlData.dialogVisible"
      title="查看流程文件"
      width="70%" >
      <xml-viewer 
              :xml="xmlContent" 
              :options="viewerOptions" 
              class="xml-viewer"
            />  
    </el-dialog>

    <!--新增流程定义-->
    <el-dialog
      v-model="template.dialogVisible"
      title="新增流程定义"
      @close="clearRuleForm"
      width="500" >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="流程名称" prop="templateName">
          <el-input v-model="ruleForm.templateName" placeholder="请输入流程名称" clearable/>
        </el-form-item>
        <el-form-item label="流程类型" prop="templateType">
          <el-select v-model="ruleForm.templateType" placeholder="请选择流程类型" clearable>
            <el-option label="资产" value="资产" />
            <el-option label="耗材" value="耗材" />
          </el-select>
        </el-form-item>
        <el-form-item label="流程定义文件" prop="file" >
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="#"
            multiple
            :on-change="handlePreview"
            :on-remove="handleRemove"
            :limit="1"
            :auto-upload="false"

            >
            <el-button type="primary">选取文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传大小不超过5MB格式位zip的文件。
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" clearable/>
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.xml-viewer {
  min-height: 400px;
  max-height: 600px;
  overflow: auto;
  margin-top: 16px;
  padding: 12px;
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  background-color: var(--el-bg-color);
}

.button-group {
  margin-top: 16px;
  display: flex;
  gap: 10px;
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>